package cn.iocoder.yudao.module.system.service.college;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeQueryReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.college.CollegeDO;
import cn.iocoder.yudao.module.system.dal.mysql.college.CollegeMapper;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

/**
 * 高校基础信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class CollegeServiceImpl implements CollegeService {

    @Resource
    private CollegeMapper collegeMapper;

    // 中国省份列表
    private static final List<String> CHINA_PROVINCES = Arrays.asList(
            "北京", "天津", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江",
            "上海", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南",
            "湖北", "湖南", "广东", "广西", "海南", "重庆", "四川", "贵州",
            "云南", "西藏", "陕西", "甘肃", "青海", "宁夏", "新疆"
    );

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveCollegeInfoList(List<CollegeInfo> collegeInfoList) {
        if (collegeInfoList == null || collegeInfoList.isEmpty()) {
            return 0;
        }

        int savedCount = 0;
        for (CollegeInfo collegeInfo : collegeInfoList) {
            try {
                // 检查是否已存在
                CollegeDO existingCollege = null;
                if (collegeInfo.getSchoolUUID() != null && !collegeInfo.getSchoolUUID().isEmpty()) {
                    existingCollege = collegeMapper.selectBySchoolUuid(collegeInfo.getSchoolUUID());
                } else if (collegeInfo.getDataId() != null && !collegeInfo.getDataId().isEmpty()) {
                    existingCollege = collegeMapper.selectByDataId(collegeInfo.getDataId());
                }

                if (existingCollege != null) {
                    // 更新现有记录
                    CollegeDO updateCollege = convertToCollegeDO(collegeInfo);
                    updateCollege.setId(existingCollege.getId());
                    collegeMapper.updateById(updateCollege);
                    log.debug("更新高校信息: {}", collegeInfo.getCollegeName());
                } else {
                    // 插入新记录
                    CollegeDO newCollege = convertToCollegeDO(collegeInfo);
                    collegeMapper.insert(newCollege);
                    log.debug("新增高校信息: {}", collegeInfo.getCollegeName());
                }
                savedCount++;
            } catch (Exception e) {
                log.error("保存高校信息失败: {}, 错误: {}", collegeInfo.getCollegeName(), e.getMessage(), e);
            }
        }

        log.info("批量保存高校信息完成，总数: {}, 成功: {}", collegeInfoList.size(), savedCount);
        return savedCount;
    }

    @Override
    public CollegeDO getCollegeByName(String collegeName) {
        List<CollegeDO> colleges = collegeMapper.selectByCollegeName(collegeName);
        return colleges.isEmpty() ? null : colleges.get(0);
    }

    @Override
    public CollegeDO getCollegeBySchoolUuid(String schoolUuid) {
        return collegeMapper.selectBySchoolUuid(schoolUuid);
    }

    @Override
    public CollegeDO getCollegeByDataId(String dataId) {
        return collegeMapper.selectByDataId(dataId);
    }

    @Override
    public List<CollegeDO> getCollegeListByProvince(String province) {
        return collegeMapper.selectByProvince(province);
    }

    @Override
    public List<CollegeDO> getCollegeListByType(String collegeType) {
        return collegeMapper.selectByCollegeType(collegeType);
    }

    @Override
    public List<CollegeDO> getCollegeListBySpecialType(Boolean is985, Boolean is211, Boolean isDualClass) {
        return collegeMapper.selectBySpecialType(is985, is211, isDualClass);
    }

    @Override
    public List<CollegeDO> getCollegeListByNameLike(String collegeName) {
        return collegeMapper.selectByCollegeNameLike(collegeName);
    }

    @Override
    public List<CollegeDO> getCollegeListByProvinceAndCity(String province, String city) {
        return collegeMapper.selectByProvinceAndCity(province, city);
    }

    @Override
    public List<CollegeDO> getCollegeListBySchoolUuids(List<String> schoolUuids) {
        return collegeMapper.selectBySchoolUuids(schoolUuids);
    }

    @Override
    public List<CollegeDO> getAllValidColleges() {
        return collegeMapper.selectAllValid();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> batchImportCollegeData(Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        int totalImported = 0;
        List<String> errors = new ArrayList<>();

        try {
            // 设置默认值
            if (pageSize == null || pageSize <= 0) {
                pageSize = 20; // API最大支持20
            }

            log.info("开始批量导入全国高校数据，每页大小: {}", pageSize);

            // 直接获取所有数据，keywords传空字符串
            totalImported = importAllCollegeData(pageSize);

            result.put("success", true);
            result.put("totalImported", totalImported);
            result.put("errors", errors);
            result.put("message", "批量导入完成，共导入 " + totalImported + " 条高校数据");

        } catch (Exception e) {
            log.error("批量导入高校数据失败", e);
            result.put("success", false);
            result.put("message", "批量导入失败: " + e.getMessage());
            result.put("totalImported", totalImported);
            result.put("errors", errors);
        }

        return result;
    }

    /**
     * 导入所有高校数据
     *
     * @param pageSize 每页大小
     * @return 导入的数据条数
     */
    private int importAllCollegeData(Integer pageSize) {
        int totalImported = 0;

        try {
            // 先获取第一页数据，确定总页数
            int firstPageCount = importCollegeDataFromApi("", 1, pageSize);
            if (firstPageCount > 0) {
                totalImported += firstPageCount;

                // 获取总数据量来计算总页数
                CollegeQueryReqVO reqVO = new CollegeQueryReqVO();
                reqVO.setKeywords(""); // 空字符串获取所有数据
                reqVO.setPagesize(pageSize);
                reqVO.setPageindex(1);

                Map<String, Object> apiResult = GuGuDataUtils.getCollegeInfo(reqVO);
                if (Boolean.TRUE.equals(apiResult.get("success"))) {
                    Integer totalCount = (Integer) apiResult.get("totalCount");
                    if (totalCount != null && totalCount > 0) {
                        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
                        log.info("总共有 {} 条高校数据，分 {} 页导入", totalCount, totalPages);

                        // 导入其他页的数据
                        for (int pageIndex = 2; pageIndex <= totalPages; pageIndex++) {
                            try {
                                int pageCount = importCollegeDataFromApi("", pageIndex, pageSize);
                                totalImported += pageCount;
                                log.info("导入第 {} 页高校数据，数量: {}，总进度: {}/{}", 
                                        pageIndex, pageCount, pageIndex, totalPages);
                                
                                // 添加请求间隔，避免API频率限制
                                Thread.sleep(1000);
                            } catch (Exception e) {
                                log.error("导入第 {} 页数据失败: {}", pageIndex, e.getMessage(), e);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("导入全国高校数据失败", e);
            throw new RuntimeException("导入全国高校数据失败: " + e.getMessage(), e);
        }

        return totalImported;
    }

    /**
     * 按省份导入高校数据
     * @deprecated 建议使用 importAllCollegeData() 方法直接获取所有数据
     *
     * @param province 省份名称
     * @param pageSize 每页大小
     * @return 导入的数据条数
     */
    @Deprecated
    private int importCollegeDataByProvince(String province, Integer pageSize) {
        int totalImported = 0;

        try {
            // 先获取第一页数据，确定总页数
            int firstPageCount = importCollegeDataFromApi(province, 1, pageSize);
            if (firstPageCount > 0) {
                totalImported += firstPageCount;

                // 获取总数据量来计算总页数
                CollegeQueryReqVO reqVO = new CollegeQueryReqVO();
                reqVO.setKeywords(province);
                reqVO.setPagesize(pageSize);
                reqVO.setPageindex(1);

                Map<String, Object> apiResult = GuGuDataUtils.getCollegeInfo(reqVO);
                if (Boolean.TRUE.equals(apiResult.get("success"))) {
                    Integer totalCount = (Integer) apiResult.get("totalCount");
                    if (totalCount != null && totalCount > 0) {
                        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

                        // 导入其他页的数据
                        for (int pageIndex = 2; pageIndex <= totalPages; pageIndex++) {
                            try {
                                int pageCount = importCollegeDataFromApi(province, pageIndex, pageSize);
                                totalImported += pageCount;
                                log.debug("导入{}省第{}页高校数据，数量: {}", province, pageIndex, pageCount);
                            } catch (Exception e) {
                                log.error("导入{}省第{}页数据失败: {}", province, pageIndex, e.getMessage(), e);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("导入{}省高校数据失败", province, e);
            throw new RuntimeException("导入" + province + "省高校数据失败: " + e.getMessage(), e);
        }

        return totalImported;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int importCollegeDataFromApi(String keywords, Integer pageIndex, Integer pageSize) {
        try {
            // 构建请求参数
            CollegeQueryReqVO reqVO = new CollegeQueryReqVO();
            reqVO.setKeywords(keywords != null ? keywords : "");
            reqVO.setPagesize(pageSize != null ? pageSize : 20);
            reqVO.setPageindex(pageIndex != null ? pageIndex : 1);

            // 调用API获取数据
            Map<String, Object> result = GuGuDataUtils.getCollegeInfo(reqVO);

            if (!Boolean.TRUE.equals(result.get("success"))) {
                throw new RuntimeException("API调用失败: " + result.get("message"));
            }

            @SuppressWarnings("unchecked")
            List<CollegeInfo> collegeList = (List<CollegeInfo>) result.get("collegeList");

            if (collegeList == null || collegeList.isEmpty()) {
                return 0;
            }

            // 保存到数据库
            return saveCollegeInfoList(collegeList);

        } catch (Exception e) {
            log.error("从API导入高校数据失败: keywords={}, pageIndex={}, pageSize={}", 
                     keywords, pageIndex, pageSize, e);
            throw new RuntimeException("从API导入高校数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 将CollegeInfo转换为CollegeDO
     */
    private CollegeDO convertToCollegeDO(CollegeInfo collegeInfo) {
        CollegeDO collegeDO = BeanUtils.toBean(collegeInfo, CollegeDO.class);
        
        // 处理字段映射
        collegeDO.setDataId(collegeInfo.getDataId());
        collegeDO.setSchoolUuid(collegeInfo.getSchoolUUID());
        collegeDO.setCollegeName(collegeInfo.getCollegeName());
        collegeDO.setProvince(collegeInfo.getProvince());
        collegeDO.setCity(collegeInfo.getCity());
        collegeDO.setDistrict(collegeInfo.getDistrict());
        collegeDO.setCoordinate(collegeInfo.getCoordinate());
        collegeDO.setCollegeType(collegeInfo.getCollegeType());
        collegeDO.setIs985(collegeInfo.getIs985());
        collegeDO.setIs211(collegeInfo.getIs211());
        collegeDO.setIsDualClass(collegeInfo.getIsDualClass());
        collegeDO.setCollegeCategory(collegeInfo.getCollegeCategory());
        // CollegeTags是字符串格式，需要解析为List<String>
        collegeDO.setCollegeTags(collegeInfo.getCollegeTagsList());
        collegeDO.setEduLevel(collegeInfo.getEduLevel());
        collegeDO.setCollegeProperty(collegeInfo.getCollegeProperty());
        collegeDO.setCollegeCode(collegeInfo.getCollegeCode());
        collegeDO.setRanking(collegeInfo.getRanking());
        collegeDO.setRankingInCategory(collegeInfo.getRankingInCategory());
        collegeDO.setWebsite(collegeInfo.getWebSite());
        collegeDO.setCallNumber(collegeInfo.getCallNumber());
        collegeDO.setEmail(collegeInfo.getEmail());
        collegeDO.setAddress(collegeInfo.getAddress());
        // BranchList是对象数组，需要转换为字符串列表
        collegeDO.setBranchList(collegeInfo.getBranchListAsStrings());
        collegeDO.setCoverImage(collegeInfo.getCoverImage());
        collegeDO.setIntro(collegeInfo.getIntro());
        collegeDO.setExpenses(collegeInfo.getExpenses());
        collegeDO.setOldName(collegeInfo.getOldName());
        collegeDO.setShortName(collegeInfo.getShortName());
        collegeDO.setMajorList(collegeInfo.getMajorList());
        // 设置新增字段
        collegeDO.setAffiliatedTo(collegeInfo.getAffiliatedTo());
        collegeDO.setIsMinistryOfEducationDirectlyAffiliated(collegeInfo.getIsMinistryOfEducationDirectlyAffiliated());
        collegeDO.setNumMaster(collegeInfo.getNumMaster());
        collegeDO.setNumDoctor(collegeInfo.getNumDoctor());
        collegeDO.setGraduateRecommendationQualificationLevel(collegeInfo.getGraduateRecommendationQualificationLevel());
        collegeDO.setIsDeleted(collegeInfo.getIsDeleted());

        return collegeDO;
    }



}
